import React from 'react'
import ReactDOM from 'react-dom'

import wx from 'wx'

import AJAX from '../../lib/ajax'
import Tools from '../../lib/tools'
import classNames from 'classnames'
import weixinShare from '../../lib/weixinShare'
import Toast from '../MyPackage/components/Toast'
import Loading from '../../components/Loading'
import { addErrorListener } from '../../lib/handleError'

require('../../lib/resetFont')
require('./Authentication.less')

const Dialog = require('../MyPackage/components/Dialog')
const send_tip1 = '国家邮政局最新规定，寄快递需实名认证'
const send_tip2 = '根据国家全面推行寄件实名制要求，寄件需要进行身份认证，以上信息仅供邮检部门校验'
const pick_tip1 = '应公安局和邮管局监管要求，取件用户需进行实名认证'
const pick_tip2 = '应公安局和邮管局监管要求，取件用户需进行实名认证，以上信息仅供公安局和邮管局查询'

class App extends React.Component {
  constructor(props) {
    super(props)
    const page_type = Tools.getParams().src
    this.state = {
      loading: false,
      loading_text: '加载中...',
      page_type, // 4种：home, personal, send, pick
      tip1: page_type === 'pick' ? pick_tip1 : send_tip1,
      tip2: page_type === 'pick' ? pick_tip2 : send_tip2,
    }
  }

  getSignature() {
    AJAX.request('get_signature', {
      full_url: window.location.href
    }, (data) => {
      wx.config({
        // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: data.body.appid, // 必填，公众号的唯一标识
        timestamp: data.body.timestamp, // 必填，生成签名的时间戳
        nonceStr: data.body.noncestr, // 必填，生成签名的随机串
        signature: data.body.signature,// 必填，签名，见附录1
        jsApiList: ['chooseImage', 'uploadImage'], // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        fail: (res) => {
          alert('wx_config_fail' + JSON.stringify(res))
        }
      })
      wx.error((res) => {
        alert('wx_error' + JSON.stringify(res))
      })
      wx.ready(() => {
        this.closeLoading()
      })
    })
  }

  componentDidMount() {
    addErrorListener()()
    weixinShare.hideAll()
    AJAX.appendBaiduAnalysis()

    this.getSignature()
    this.getAuthStatus()
  }

  getAuthStatus() {
    AJAX.request('user_home', {}, (data) => {
      const { code, body } = data;
      const { is_id_authed } = body;
      if (code === 0 && is_id_authed !== 0) {
        Dialog.info({
          title: '出错了',
          content: '当前用户已认证',
          okText: '确认',
          onOK: () => {
            window.location.replace('./MyPackage')
          }
        })
      }
    })
  }

  openLoading(type) {
    let loading_text, loading = true
    if (type === 'identify') {
      loading_text = '识别中...'
    }
    this.setState({
      loading_text,
      loading
    })
  }

  closeLoading() {
    this.setState({
      loading: false,
      loading_text: '加载中'
    })
  }

  //删除重拍
  delete() {
    this.setState({
      id_front: null,
      id_end: null,
      idcard_back_media_id: null,
      idcard_front_media_id: null,
      identify_info: null
    })
  }

  //选择图片
  handleImg(type) {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        var localIds = res.localIds // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
        if (type === 'ZHENG') {
          this.setState({
            id_front: localIds[0],
          })
          this.upload(localIds[0], 'ZHENG')
        } else if (type === 'FAN') {
          this.setState({
            id_end: localIds[0],
          })
          this.upload(localIds[0], 'FAN')
        }
      },
      fail: (res) => {
        alert('wx_chooseImage_fail' + JSON.stringify(res))
      }
    })
  }

  upload(imgSrc, type) {
    wx.uploadImage({
      localId: imgSrc, // 需要上传的图片的本地ID，由chooseImage接口获得
      isShowProgressTips: 1, // 默认为1，显示进度提示
      success: (res) => {
        if (type === 'ZHENG') {
          this.setState({
            idcard_front_media_id: res.serverId,
          }, () => {
            if (this.state.idcard_back_media_id) {
              this.identify()
            }
          })
        } else if (type === 'FAN') {
          this.setState({
            idcard_back_media_id: res.serverId,
          }, () => {
            if (this.state.idcard_front_media_id) {
              this.identify()
            }
          })
        }
      },
      fail: function () {
        isSend = true
      }
    })
  }

  //进行图像识别
  identify = () => {
    this.openLoading('identify');

    const { idcard_front_media_id, idcard_back_media_id } = this.state;
    const params = {
      idcard_front_media_id,
      idcard_back_media_id,
    };

    AJAX.request('identify', params, (data) => {
      this.closeLoading()
      if (data.code === 0) {
        this.setState({ loading: false })

        if (data.body.error_msg) {
          Toast.error({
            type: 'new',
            content: data.body.error_msg
          })
        } else {
          const identify_info = {
            name: data.body.name, // 姓名
            idcard_num: data.body.idcard_num, // 身份证号
            gender: data.body.gender, // 性别(1:男, 2:女)
            nation: data.body.nation, // 民族
            birthday: data.body.birthday, // 出生日期，例: 1990-10-11
            address: data.body.address, // 住址
          }
          this.setState({ identify_info });
        }
      }
    })
  }

  submit() {
    const { page_type } = this.state;

    AJAX.request('id_auth_submit', {}, (data) => {
        if (data.code === 0) {
          Toast.success({
            type: 'new',
            content: '认证成功',
            duration: 1000
          })
          setTimeout(() => {
            if (page_type === 'push') {
              window.location.replace('./MyPackage')
              return
            }
            history.back();
          }, 1000)
        }
      })
  }

  handleSubmit() {
    const {
      loading,
      identify_info,
      idcard_back_media_id,
      idcard_front_media_id,
    } = this.state;
    
    if (loading) {
      return
    }
    
    if (!idcard_front_media_id) {
      Toast.error({
        type: 'new',
        content: '未上传正面照片',
      })
      return
    }

    if (!idcard_back_media_id) {
      Toast.error({
        type: 'new',
        content: '未上传反面照片'
      })
      return
    }

    if (!identify_info) {
      Toast.error({
        type: 'new',
        content: '正面照片无法识别，请重新上传'
      })
      return
    }

    return this.submit();
  }

  makeExample() {
    return (
      <div className="id-desc lux-mt34 plu-pr38 lux-pt36 lux-pb36">
        <div className="idd-title lux-pb20 lux-pl38">
          请上传清晰的证件图像，以便快速通过(如下1图示例)
        </div>

        <div className="idd-content lux-mt30">
          <div className="iddc-cell">
            <div className="iddcc-img lux-h120 lux-w200">
              <img src={`//cdn2.jinlb.cn/pic/ab/9b/ab9b7a556fad54499a0836da42717eb9.png`} />
            </div>
            <div className="iddcc-desc lux-mt10 lux-w200 lux-center">
              <i className="iconfont icon-duigou lux-pr5" />
              标准
            </div>
          </div>
          <div className="iddc-cell lux-ml10">
            <div className="iddcc-img lux-h120 lux-w200">
              <img src={`//cdn2.jinlb.cn/pic/1e/ed/1eed69ed47b7588d9358a52806cb39aa.png`} />
            </div>
            <div className="iddcc-desc lux-mt10 lux-w200 lux-center">
              <i className="iconfont icon-cuowu lux-pr5" />
              缺少边框
            </div>
          </div>
          <div className="iddc-cell lux-ml10">
            <div className="iddcc-img lux-h120 lux-w200">
              <img src={`//cdn2.jinlb.cn/pic/2a/5a/2a5af240f2e6de15735b0943672b0d13.png`} />
            </div>
            <div className="iddcc-desc lux-mt10 lux-w200 lux-center">
              <i className="iconfont icon-cuowu lux-pr5" />
              照片模糊
            </div>
          </div>
          <div className="iddc-cell lux-ml10">
            <div className="iddcc-img lux-h120 lux-w200">
              <img src={`//cdn2.jinlb.cn/pic/8c/74/8c7412ba97e4a2a2f1776e5f2cf32516.png`} />
            </div>
            <div className="iddcc-desc lux-mt10 lux-w200 lux-center">
              <i className="iconfont icon-cuowu lux-pr5" />
              闪光强烈
            </div>
          </div>
        </div>
      </div>
    )
  }

  makeIndetifyInfo(identify_info = {}) {
    const {
      name,
      idcard_num,
      gender,
      nation,
      birthday,
      address,
    } = identify_info

    const gender_male_cls = classNames('iconfont lux-mr12', {
      'icon-duigou': gender === 1,
      'icon-iconfontwancheng': gender !== 1
    });

    const gender_female_cls = classNames('iconfont  lux-ml40 lux-mr12', {
      'icon-duigou': gender === 2,
      'icon-iconfontwancheng': gender !== 2
    });

    return (
      <div className="id-info lux-mt34 lux-pt10 lux-pb10 lux-pl38 lux-pr38">
        <div className="idi-cell">
          <div className="idic-label lux-w160">
            姓名
          </div>
          <div className="idic-text lux-center">
            {name}
          </div>
        </div>
        <div className="idi-cell ">
          <div className="idic-label lux-w160">
            性别
          </div>
          <div className="idic-text lux-center">
            <i className={gender_male_cls} />
            男
            <i className={gender_female_cls} />
            女
          </div>
        </div>
        <div className="idi-cell">
          <div className="idic-label lux-w160">
            民族
          </div>
          <div className="idic-text lux-center">
            {nation}
          </div>
        </div>
        <div className="idi-cell">
          <div className="idic-label lux-w160">
            出生日期
          </div>
          <div className="idic-text lux-center">
            {birthday}
          </div>
        </div>
        <div className="idi-cell">
          <div className="idic-label lux-w160">
            住址
          </div>
          <div className="idic-text lux-center">
            {address}
          </div>
        </div>
        <div className="idi-cell no-border">
          <div className="idic-label lux-w160">
            身份证号
          </div>
          <div className="idic-text lux-center">
            {idcard_num}
          </div>
        </div>
      </div>
    )
  }

  render() {
    const {
      id_front,
      id_end,
      identify_info,
      tip1,
      tip2,
      loading,
      loading_text,
    } = this.state

    return (
      <div className="Authentication">
        <div className="warn lux-h80 lux-center">
          <i className="iconfont icon-iconfontjinggao lux-pt4 lux-pr10" />
          {tip1}
        </div>

        <div className="id-card lux-pt20">
          <div className="idc-title lux-pl30 lux-pr30">
            <div className="idct-left">
              <i className="iconfont icon-tupian lux-mr10" />
              身份证照
            </div>
            <div className="idct-right">
              <a href="javascript:" onClick={this.delete.bind(this)}>删除重拍</a>
              <i className="iconfont icon-jiantou1" />
            </div>
          </div>
          <div className="idc-content lux-mt20 lux-pb30 lux-pl30 lux-pr30">
            <div
              className="idcc-area lux-w340 lux-h220"
              onClick={this.handleImg.bind(this, 'ZHENG')}
            >
              {
                id_front
                  ? <img src={id_front} alt="" />
                  : <div>
                    <img src={`//cdn2.jinlb.cn/pic/f2/b0/f2b03757395ff45dd9363b4037ca4e71.png`} />
                    <div className="idcca-desc lux-center lux-h48">
                      身份证正面
                    </div>
                  </div>
              }
            </div>
            <div
              className="idcc-area lux-w340 lux-h220 lux-h48 lux-ml20"
              onClick={this.handleImg.bind(this, 'FAN')}
            >
              {
                id_end
                  ? <img src={id_end} alt="" />
                  : <div>
                    <img src={`//cdn2.jinlb.cn/pic/98/41/98412c59f359bb83ff4c063080693ee7.png`} />
                    <div className="idcca-desc lux-center lux-h48">
                      身份证反面
                    </div>
                  </div>
              }
            </div>
          </div>
          <div className="idc-warn lux-h120 lux-center lux-pl30 lux-pr30">
            <i className="iconfont icon-iconfontjinggao lux-mr12" />
            <p>{tip2}</p>
          </div>
        </div>

        {
          identify_info
            ? this.makeIndetifyInfo(identify_info)
            : this.makeExample()
        }

        <div 
          className="id-button lux-mt50 lux-w675 lux-h73 lux-center green" 
          onClick={this.handleSubmit.bind(this)}
        >
          提交认证
        </div>

        <Loading text={loading_text} show={loading} />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'))
if (module.hot) {
  module.hot.accept()
}